package cn.rkylin.oms.base.returnReasonType.controller;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;

import cn.rkylin.core.ApolloMap;
import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.oms.base.returnReasonType.dao.ReturnReasonTypeDAOImpl;
import cn.rkylin.oms.base.returnReasonType.domain.ReturnReasonType;
import cn.rkylin.oms.base.returnReasonType.service.ReturnReasonTypeService;
import cn.rkylin.oms.base.returnReasonType.vo.ReturnReasonTypeVO;
import cn.rkylin.oms.common.annotation.SystemControllerLog;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.common.dto.DBLog;
import cn.rkylin.oms.common.utils.LogUtil;

/**
 * 退货原因类型控制器
 *
 * @author qitao
 * @version 1.0
 * @created 17-7月-2017
 */
@Controller
@RequestMapping("/returnReasonType")
public class ReturnReasonTypeController extends ApolloController {

	private static final String PAGE_SELECT_STATEMENT = "pageSelectReturnReasonType";

	@Autowired
	public ReturnReasonTypeService returnReasonTypeService;

	@Autowired
	private LogUtil logUtil;

	/**
	 * 查询退货原因类型
	 * 
	 * @param quickSearch
	 *            快速查询
	 * @param start
	 *            开始页码
	 * @param length
	 *            页数
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@ResponseBody
	@RequestMapping(value = "/getReturnReasonTypeList")
	public Map getReturnReasonTypeList(String quickSearch,
			@RequestParam(required = false, defaultValue = "0") int start,
			@RequestParam(required = false, defaultValue = "10") int length) throws Exception {

		Map map = new HashMap();
		try {
			quickSearch = URLDecoder.decode(quickSearch, "UTF-8");
			// 处理分页
			if (length == -1) {
				length = Integer.MAX_VALUE;
			}
			int page = start / length + 1;
			ReturnReasonTypeVO param = new ReturnReasonTypeVO();
			if (!StringUtils.isEmpty(quickSearch)) {
				param.setReturnReasonName(quickSearch);
			}

			// 处理转义的字段
			Map<String, String> replaceFieldsMap = new HashMap<String, String>();
			replaceFieldsMap.put("enableStatus", "enable");

			// 排序语句生成
			String orderStatement = getOrderString(ReturnReasonTypeDAOImpl.class.getName(), PAGE_SELECT_STATEMENT,
					replaceFieldsMap);
			if (StringUtils.isNotEmpty(orderStatement)) {
				param.setOrderBy(orderStatement);
			}

			PageInfo<ReturnReasonTypeVO> returnReasonTypeVOList = returnReasonTypeService.findByWhere(page, length,
					param);
			map.put(JSON_RESULT, SUCCESS);
			map.put("recordsFiltered", returnReasonTypeVOList.getTotal());
			map.put("recordsTotal", returnReasonTypeVOList.getTotal());
			map.put(RETURN_DATA, returnReasonTypeVOList.getList());

		} catch (Exception ex) {
			ex.printStackTrace();
			map.put("result", "failed");
			map.put("msg", ex.getMessage());
		}

		return map;
	}

	/**
	 * 校验退货原因类型是否存在
	 * 
	 * @param returnReasonCode
	 *            退货原因编码
	 */
	private int validReturnReasonCode(String returnReasonCode, String returnReasonName) throws Exception {
		ApolloMap<String, Object> params = new ApolloMap<String, Object>();
		params.put("returnReasonCode", returnReasonCode);
		params.put("returnReasonName", returnReasonName);

		int existsPrj = returnReasonTypeService.getReturnReasonTypeCountByCode(params);

		return existsPrj;
	}

	/**
	 * 插入退货原因类型
	 * 
	 * @param returnReasonType
	 *            退货原因类型
	 */
	@SuppressWarnings("rawtypes")
	@ResponseBody
	@RequestMapping(value = "/insertReturnReasonType")
	@SystemControllerLog(module = "退货原因类型", operation = "插入退货原因类型", keyCode = "returnReasonId")
	public Map<String, String> insertReturnReasonType(@RequestBody ReturnReasonType returnReasonType) throws Exception {
		CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
		Iterator iterator = currentUser.getEnterpriseMap().keySet().iterator();
		String entId = (String) iterator.next();

		ApolloMap<String, Object> params = new ApolloMap<String, Object>();
		String returnReasonId = java.util.UUID.randomUUID().toString().replace("-", "");
		params.put("returnReasonId", returnReasonId);
		params.put("returnReasonCode", returnReasonType.getReturnReasonCode());
		params.put("returnReasonName", returnReasonType.getReturnReasonName());
		params.put("remark", returnReasonType.getRemark());
		params.put("deleted", VALUE_NO);
		params.put("entId", entId);
		Map<String, String> map = new HashMap<String, String>();
		if (validReturnReasonCode(returnReasonType.getReturnReasonCode(), returnReasonType.getReturnReasonName()) == 1) {
			map.put("result", FAILED);
			map.put("msg", "退货原因已存在");
		} else {
			returnReasonTypeService.insertReturnReasonType(params);
			map.put("result", SUCCESS);
			map.put("returnReasonId", returnReasonId);
		}

		logUtil.info(new DBLog(returnReasonId, returnReasonType.getReturnReasonName(), "创建退货原因类型 ", params.toString()));
		map.put("returnReasonId", returnReasonType.getReturnReasonId());
		return map;
	}

	/**
	 * 查询退货原因类型
	 * 
	 * @param returnReasonId
	 *            原因Id
	 */
	@ResponseBody
	@RequestMapping(value = { "/getReturnReasonTypeInfo/{returnReasonId}" })
	public Map<String, Object> getReturnReasonTypeInfo(@PathVariable String returnReasonId) throws Exception {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("returnReasonId", returnReasonId);
			ReturnReasonType returnReasonType = returnReasonTypeService.getReturnReasonTypeInfo(params);
			if (returnReasonType != null) {
				returnMap.put(JSON_RESULT, SUCCESS);
				returnMap.put(RETURN_DATA, returnReasonType);
			} else {
				returnMap.put(JSON_RESULT, FAILED);
				returnMap.put(JSON_MSG, "该退货原因类型不存在");
			}
		} catch (Exception ex) {
			logUtil.error(ex.getMessage(), ex);
			returnMap.put(JSON_RESULT, FAILED);
			returnMap.put(JSON_MSG, ex.getMessage());
		}

		return returnMap;
	}

	/**
	 * 修改退货原因类型
	 * 
	 * @param returnReasonType
	 *            退货原因类型
	 */
	@ResponseBody
	@RequestMapping(value = "/updateReturnReasonType")
	@SystemControllerLog(module = "退货原因类型", operation = "修改退货原因类型", keyCode = "returnReasonId")
	public Map<String, String> updateReturnReasonType(@RequestBody ReturnReasonType returnReasonType) throws Exception {
		ApolloMap<String, Object> params = new ApolloMap<String, Object>();
		params.put("returnReasonId", returnReasonType.getReturnReasonId());
		params.put("returnReasonCode", returnReasonType.getReturnReasonCode());
		params.put("returnReasonName", returnReasonType.getReturnReasonName());
		params.put("remark", returnReasonType.getRemark());

		Map<String, String> map = new HashMap<String, String>(1);

		returnReasonTypeService.updateReturnReasonType(params);
		map.put("result", "true");

		logUtil.info(new DBLog(returnReasonType.getReturnReasonId(), "更改退货原因类型", returnReasonType.getReturnReasonName(),
				params.toString()));
		map.put("returnReasonId", returnReasonType.getReturnReasonId());
		return map;
	}

	/**
	 * 删除退货原因类型
	 * 
	 * @param returnReasonId
	 *            原因Id
	 */
	@ResponseBody
	@RequestMapping(value = { "/deleteReturnReasonType/{returnReasonId}" })
	@SystemControllerLog(module = "退货原因类型", operation = "删除退货原因类型", keyCode = "returnReasonId")
	public Map<String, Object> deleteReturnReasonType(@PathVariable String returnReasonId) throws Exception {
		ApolloMap<String, Object> params = new ApolloMap<String, Object>();
		params.put("returnReasonId", returnReasonId);
		params.put("deleted", VALUE_YES);

		returnReasonTypeService.deleteReturnReasonType(params);

		logUtil.info(new DBLog(returnReasonId, "删除退货原因类型", "", params.toString()));

		Map<String, Object> map = new HashMap<String, Object>(1);
		map.put("success", true);
		map.put("returnReasonId", returnReasonId);
		return map;
	}

}
